package cn.dapeng.ticket;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.*;

public class CountdownLatchT2 {

    public static void main(String[] args) {
        System.out.println(m1());

        System.out.println(" ========================= ");

        System.out.println(m2());
    }

    public static int m1() {
        long startTime = System.currentTimeMillis();
        int r = t1() + t2() + t3() + t4();
        System.out.println("耗时：" + (System.currentTimeMillis() - startTime));
        return r;
    }

    public static int m2() {
        long startTime = System.currentTimeMillis();
        final CountDownLatch countDownLatch = new CountDownLatch(4);
        ExecutorService executor = Executors.newFixedThreadPool(4);

        try {
            Future<Integer> f1 = executor.submit(() -> t1());
            Future<Integer> f2 = executor.submit(() -> t2());
            Future<Integer> f3 = executor.submit(() -> t3());
            Future<Integer> f4 = executor.submit(() -> t4());

            int r1 = f1.get();
            countDownLatch.countDown();
            int r2 = f2.get();
            countDownLatch.countDown();
            int r3 = f3.get();
            countDownLatch.countDown();
            int r4 = f4.get();
            countDownLatch.countDown();
            countDownLatch.await();
            executor.shutdown();
            System.out.println("耗时：" + (System.currentTimeMillis() - startTime));
            return r1 + r2 + r3 + r4;
        } catch (Exception e) {

        }
        return 0;
    }

    public static int t1() {
        SleepingUtil.sleep(1, TimeUnit.SECONDS);
        return 1;
    }

    public static int t2() {
        SleepingUtil.sleep(2, TimeUnit.SECONDS);
        return 2;
    }

    public static int t3() {
        SleepingUtil.sleep(3, TimeUnit.SECONDS);
        return 3;
    }

    public static int t4() {
        SleepingUtil.sleep(4, TimeUnit.SECONDS);
        return 4;
    }
}
